from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import redirect
from django.core.urlresolvers import reverse

from common.models import Product,Category,Shop,User

def index(request):
    '''前台首页'''
    context = {}
    #根据当前店铺id获取所对应的商品类别信息
    clist = Category.objects.filter(shop_id=request.session['shopinfo']['id'],status=1)
    #遍历菜品类别信息，查询每个菜品类别下对应的所有菜品信息，并以pids属性存放
    for vo in clist:
        vo.pids = Product.objects.filter(category_id=vo.id,status=1)
    context["clist"]=clist
    if 'foodlist' not in request.session:
        request.session['foodlist'] = {}
    totalprice = 0
    for food in request.session['foodlist'].values():
        totalprice += food['price']*food['m']
    request.session['totalprice'] = totalprice
    context["pagetype"] = 0
    return render(request,"web/index.html",context)

def login(request):
    '''前台登录页面'''
    shopslist = Shop.objects.all()
    context = {"shopslist":shopslist}
    #login页面将根据typeinfo来显示错误信息
    context["typeinfo"]=int(request.GET.get("typeinfo",0))
    return render(request,"web/login.html",context)

def dologin(request):
    '''前台执行登录'''
    # 校验是否选择店铺
    shopid = request.POST['shop_id']
    if int(shopid) == 0: #未选择店铺
        return redirect(reverse('web_login')+'?typeinfo=1')
    #将已选择的商铺信息放入到session中
    selectedShop = Shop.objects.get(id=shopid)
    request.session['shopinfo'] = selectedShop.toDict()
    # 校验验证码
    verifycode = request.session['verifycode']
    code = request.POST['code']
    if verifycode != code:
        return redirect(reverse('web_login')+'?typeinfo=2')

    try:
        #根据账号获取登录者信息
        user = User.objects.get(username=request.POST['username'])
        #判断当前用户状态是否正常
        if user.status == 1:
            # 验证密码
            import hashlib
            m = hashlib.md5() 
            pw = request.POST['password'] + user.password_salt
            m.update(pw.encode('utf-8'))
            if user.password_hash == m.hexdigest():
                # 此处登录成功，将当前登录信息放入到session中，并跳转页面
                request.session['vipuser'] = user.toDict()
                return redirect(reverse('web_index'))
            else:
                typeinfo = 3
        else:
            typeinfo = 4
    except Exception as err:
        print(err)
        typeinfo = 5
    return redirect('%s?typeinfo=%d'%(reverse('web_login'),typeinfo))

def logout(request):
    '''前台退出'''
    # 清除登录的session信息
    del request.session['vipuser']
    # 跳转登录页面（url地址改变）
    return redirect(reverse('web_login'))

def verify(request):
    #引入随机函数模块
    import random
    from PIL import Image, ImageDraw, ImageFont
    #定义变量，用于画面的背景色、宽、高
    #bgcolor = (random.randrange(20, 100), random.randrange(
    #    20, 100),100)
    bgcolor = (242,164,247)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象，ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('static/STXIHEI.TTF', 21)
    #font = ImageFont.load_default().font
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    """
    python2的为
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')